<?php
/**
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/28
 */

namespace app\api\model;


use think\model;

/**
 * 管理员操作记录
 * Class SystemLog
 * @package app\admin\model\system
 */
class SystemLog extends model
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'eb_api_log';

    protected $insert = ['add_time'];

    protected function setAddTimeAttr()
    {
        return time();
    }


    /**
     * 管理员访问记录
     *
     * @param $adminId
     * @param $adminName
     * @param $type
     * @return SystemLog|\think\Model
     */
    public static function adminVisit($adminId,$adminName)
    {
        $request = app('request');
        $controller = $request->controller();
        $action = $request->action();
        $domain= $request->domain();
        $page = $request->method();
        $param = $request->param();
        self::startTrans();
        try{
            $data = [
                'method'=>'api/'.$controller.'/'.$action,
                'uid'=>$adminId,
                'add_time'=>time(),
                'name'=>$adminName,
                'path'=>$domain,
                'page'=>$page,
                'ip'=>$request->ip(),
                'param'=>json_encode($param),
            ];
            $res = self::create($data);
            if($res){
                self::commit();
                return true;
            }else{
                self::rollback();
                return false;
            }
        }catch (\Exception $e){
            self::rollback();
            return self::setErrorInfo($e->getMessage());
        }

    }

    /**
     * 手动添加管理员当前页面访问记录
     * @param array $adminInfo
     * @param string $page 页面名称
     * @return object
     */
    public static function setCurrentVisit($adminInfo, $page)
    {
        $request = app('request');
        $module = app('http')->getName();
        $controller = $request->controller();
        $action = $request->action();
        $route = $request->route();
        $data = [
            'method'=>$request->method(),
            'admin_id'=>$adminInfo['id'],
            'path'=>1,
            'page'=>$page,
            'ip'=>$request->ip()
        ];
        return self::create($data);
    }

}